<script setup>
/**
 * 企业端报表列表页面（Dashboard）
 * - 显示所有历史报表
 * - 区分暂存和已提交状态
 * - 可以新建报表
 */
import { onMounted, ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import {
    Document,
    Plus,
    View,
    Edit,
    Timer,
    Clock,
    User,
    UserFilled,
    WarningFilled,
    Right,
} from '@element-plus/icons-vue';
import { fetchReportList, fetchAuditHistory, fetchReportHistory } from '@/api/report';

// 路由实例
const router = useRouter();

// 从 localStorage 获取登录用户信息
const getEnterpriseInfo = () => {
    try {
        const enterpriseInfoStr = localStorage.getItem('enterpriseInfo');
        if (enterpriseInfoStr) {
            return JSON.parse(enterpriseInfoStr);
        }
    } catch (error) {
        console.error('获取企业信息失败:', error);
    }
    return null;
};

const enterpriseInfo = getEnterpriseInfo();

// 响应式数据
const loading = ref(false);
const reportList = ref([]);
const versionCountMap = ref({});
const enterpriseId = ref(enterpriseInfo?.enterpriseId || 'ENTERPRISE_001'); // 从登录信息获取
const showHistoryDialog = ref(false);
const selectedPeriodHistory = ref([]);
const auditHistoryByReportId = ref({});

/**
 * 统一解析报表ID，兼容历史版本返回 report_id 等字段
 */
const resolveReportId = (report) => {
    if (!report || typeof report !== 'object') return null;
    return report.id ?? report.report_id ?? report.reportId ?? null;
};

/**
 * 状态标签配置
 */
const statusConfig = {
    '-1': { label: '未填报', type: 'info', icon: Document },
    0: { label: '已暂存', type: 'warning', icon: Edit },
    1: { label: '待市级审核', type: 'warning', icon: Document }, // Updated to 'warning' for CSS mapping
    2: { label: '待省级审核', type: 'primary', icon: Document },
    3: { label: '审核通过', type: 'success', icon: Document },
    4: { label: '已归档', type: 'info', icon: Document },
    5: { label: '驳回', type: 'danger', icon: Edit },
};

/**
 * 加载报表列表
 */
const loadReportList = async () => {
    loading.value = true;
    try {
        const data = await fetchReportList({
            page_no: 1,
            page_size: 100,
        });

        const nextVersionCount = {};
        (data || []).forEach((report) => {
            if (report?.reporting_period) {
                nextVersionCount[report.reporting_period] = report.version_count || 1;
            }
        });
        versionCountMap.value = nextVersionCount;
        seedAuditSnapshots(data || []);

        reportList.value = (data || [])
            .sort((a, b) => b.reporting_period.localeCompare(a.reporting_period))
            .map((report, index) => ({
                ...report,
                rowNo: index + 1,
                fill_time: formatDate(report.updated_at),
                period_range: formatPeriodRange(report.period_start_time, report.period_end_time),
            }));
    } catch (error) {
        ElMessage.error(error?.message || '加载报表列表失败');
    } finally {
        loading.value = false;
    }
};

/**
 * 跳转到新建报表页面
 */
const handleCreateReport = () => {
    router.push('/report/form');
};

/**
 * 查看/编辑报表详情
 */
const handleViewReport = (report) => {
    const reportId = resolveReportId(report);
    if (!reportId && !report?.reporting_period) {
        ElMessage.error('未找到对应的报表信息');
        return;
    }

    const query = {
        period: report.reporting_period,
    };

    // 仅在不可编辑或历史版本时强制只读
    if (!report?.editable && reportId) {
        query.id = reportId;
        query.editable = '0';
    }

    router.push({
        path: '/report/form',
        query,
    });
};

/**
 * 格式化日期显示
 */
const formatDate = (dateStr) => {
    if (!dateStr) return '-';
    const date = new Date(dateStr);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
    });
};

const formatPeriodRange = (startTime, endTime) => {
    if (!startTime || !endTime) return '-';
    const start = new Date(startTime);
    const end = new Date(endTime);
    const formatDatePart = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}年${month}月${day}日`;
    };
    return `${formatDatePart(start)} - ${formatDatePart(end)}`;
};

const formatAuditTime = (timeStr) => {
    if (!timeStr) return '-';
    if (timeStr.includes('T')) {
        return formatDate(timeStr);
    }
    return timeStr;
};

// 获取调查期的时间
const formatInvestigateTimeDisplay = (period) => {
    if (!period) return '-';
    const [year, month] = period.split('-');
    if (!month) return period;
    return `${year}年${month}月`;
};

const getTimelineType = (row) => {
    const status = String(row?.status ?? '');
    if (status === '3' || status === '4') return 'success';
    if (status === '5') return 'danger';
    if (status === '2') return 'primary';
    if (status === '1') return 'warning';
    return 'info';
};

const getTimelineColor = (type) => {
    const map = {
        success: '#10b981',
        danger: '#ef4444',
        primary: '#3b82f6',
        warning: '#f97316',
        info: '#94a3b8',
    };
    return map[type] || '#94a3b8';
};

/**
 * 计算减员人数
 */
const getStaffChangeValue = (report) => {
    if (
        typeof report.initial_employees === 'number' &&
        typeof report.current_employees === 'number'
    ) {
        return report.current_employees - report.initial_employees;
    }
    return null;
};

const formatStaffChangeValue = (report) => {
    const diff = getStaffChangeValue(report);
    if (diff == null) return '-';
    if (diff === 0) return '0';
    return diff > 0 ? `+${diff}` : `${diff}`;
};

const getStaffChangeClass = (report) => {
    const diff = getStaffChangeValue(report);
    if (diff == null) return 'change-indicator--unknown';
    if (diff > 0) return 'change-indicator--increase';
    if (diff < 0) return 'change-indicator--decrease';
    return 'change-indicator--flat';
};

/**
 * 查看某个调查期的历史版本
 */
const handleViewHistory = async (reportingPeriod) => {
    try {
        const history = await fetchReportHistory({ reporting_period: reportingPeriod });
        const normalized = (history || [])
            .sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
            .map((report, index) => ({
                ...report,
                rowNo: index + 1,
                fill_time: formatDate(report.updated_at),
                period_range: formatPeriodRange(report.period_start_time, report.period_end_time),
            }));
        selectedPeriodHistory.value = normalized;
        seedAuditSnapshots(normalized);
        await loadAuditHistoryForPeriod(reportingPeriod);
        showHistoryDialog.value = true;
    } catch (error) {
        ElMessage.error(error?.message || '加载历史版本失败');
    }
};

/**
 * 统计某个调查期的版本数量
 */
const getVersionCount = (reportingPeriod) => {
    if (!reportingPeriod) return 0;
    return versionCountMap.value[reportingPeriod] || 1;
};

const seedAuditSnapshots = (reports = []) => {
    const next = { ...auditHistoryByReportId.value };
    reports.forEach((report) => {
        const reportId = resolveReportId(report);
        if (!report || !reportId) return;

        if (
            report.latest_audit_level == null &&
            report.latest_audit_result == null &&
            !report.latest_audit_opinion &&
            !report.latest_audit_time
        ) {
            return;
        }

        const snapshot = {
            audit_level: report.latest_audit_level,
            audit_level_name: report.latest_audit_level_name,
            audit_result: report.latest_audit_result,
            audit_result_name: report.latest_audit_result_name,
            audit_opinion: report.latest_audit_opinion,
            audit_time: report.latest_audit_time,
        };

        next[reportId] = {
            latest: snapshot,
            latestReject: report.latest_audit_result === 2 ? snapshot : null, // Assuming 2 is reject in backend logic, check if it's 5
        };
        // Note: In statusConfig 5 is reject. Ensure backend logic matches.
        // If backend result 2 means reject, keep as is.
    });
    auditHistoryByReportId.value = next;
};

const buildAuditIndex = (historyList = []) => {
    const map = {};
    historyList.forEach((item) => {
        const reportId = item.report_id;
        if (!reportId) return;
        if (!map[reportId]) map[reportId] = [];
        map[reportId].push(item);
    });

    const result = {};
    Object.keys(map).forEach((reportId) => {
        const sorted = map[reportId]
            .filter((record) => record.audit_time)
            .sort((a, b) => new Date(b.audit_time) - new Date(a.audit_time));
        const latestReject = sorted.find((record) => record.audit_result === 2);
        result[reportId] = {
            latest: sorted[0] || null,
            latestReject,
        };
    });

    const merged = { ...auditHistoryByReportId.value };
    Object.keys(result).forEach((reportId) => {
        const snapshot = result[reportId];
        if (!merged[reportId]) {
            merged[reportId] = snapshot;
            return;
        }
        merged[reportId] = {
            latest: snapshot.latest || merged[reportId].latest,
            latestReject: snapshot.latestReject || merged[reportId].latestReject,
        };
    });
    auditHistoryByReportId.value = merged;
};

const loadAuditHistoryForPeriod = async (reportingPeriod) => {
    try {
        const data = await fetchAuditHistory({ reporting_period: reportingPeriod });
        buildAuditIndex(data?.audit_history || []);
    } catch (error) {
        console.error('加载审核历史失败:', error);
    }
};

const getRejectInfo = (row) => {
    const fallback = {
        department: row?.latest_audit_level_name || '-',
        reason: row?.latest_audit_opinion || '-',
        time: row?.latest_audit_time ? formatAuditTime(row.latest_audit_time) : '-',
    };

    const rowId = resolveReportId(row);
    const info = rowId ? auditHistoryByReportId.value[rowId] : null;
    if (!info || !info.latestReject) {
        return fallback;
    }
    const { latestReject } = info;
    return {
        department:
            latestReject.audit_level_name || latestReject.audit_level || fallback.department,
        reason: latestReject.audit_opinion || fallback.reason,
        time: latestReject.audit_time ? formatAuditTime(latestReject.audit_time) : fallback.time,
    };
};

const historyTimelineData = computed(() => {
    return (selectedPeriodHistory.value || []).map((item, index) => {
        const rejectInfo = getRejectInfo(item);
        const statusKey = String(item?.status ?? '');
        const statusMeta = statusConfig[statusKey] || {};
        const rejectSection = item?.reason_return || item?.reasonReturn || '';

        // Check if it's a rejected status
        const isRejectedStatus = statusKey === '5';

        return {
            ...item,
            __key: resolveReportId(item) || `${item.reporting_period}-${index}`,
            __statusLabel: statusMeta.label || statusKey,
            __statusType: statusMeta.type || 'info',
            __timelineType: getTimelineType(item),
            __rejectInfo: rejectInfo,
            __showReject: isRejectedStatus,
            __rejectSection: rejectSection,
        };
    });
});

onMounted(() => {
    loadReportList();
});
</script>

<template>
    <div class="report-list-demo">
        <!-- Header -->
        <div class="page-header">
            <div class="header-left">
                <!-- <div class="header-icon"><el-icon>
            <document />
          </el-icon></div> -->
                <div>
                    <h1 class="page-title">数据填报管理</h1>
                    <p class="page-description">查看和管理您的报表填报记录</p>
                </div>
            </div>
        </div>

        <!-- Operation Bar (Create Button) -->
        <div class="table-operations">
            <el-button
                type="primary"
                size="large"
                :icon="Plus"
                @click="handleCreateReport"
                class="create-btn btn-primary-theme"
            >
                新建报表
            </el-button>
        </div>

        <!-- Content -->
        <div class="report-content" v-loading="loading">
            <!-- Empty State -->
            <div v-if="!loading && reportList.length === 0" class="empty-state-card">
                <el-empty image-size="200" description="暂无报表数据">
                    <el-button
                        type="primary"
                        :icon="Plus"
                        @click="handleCreateReport"
                        class="btn-primary-theme"
                    >
                        立即创建第一份报表
                    </el-button>
                </el-empty>
            </div>

            <!-- Table -->
            <div v-else class="table-card">
                <el-table
                    :data="reportList"
                    style="width: 100%"
                    class="modern-table"
                    :header-cell-style="{
                        background: '#f8fafc',
                        color: '#475569',
                        fontWeight: '700',
                        fontSize: '13px',
                        height: '56px',
                        textAlign: 'center',
                    }"
                    :cell-style="{ textAlign: 'center' }"
                    :row-style="{ height: '80px' }"
                >
                    <!-- 0. No. Column -->
                    <el-table-column label="No." width="60" align="center">
                        <template #default="{ row }">
                            <span class="row-number">{{ row.rowNo }}</span>
                        </template>
                    </el-table-column>

                    <!-- 1. Period Column -->
                    <el-table-column label="调查期 / 填报时间" min-width="260" align="center">
                        <template #default="{ row }">
                            <div style="text-align: left; display: inline-block">
                                <div class="cell-primary-text">
                                    {{ formatInvestigateTimeDisplay(row.reporting_period) }}
                                </div>
                                <div class="cell-secondary-text">
                                    <!-- <el-icon class="mr-1">
                    <timer />
                  </el-icon>  -->
                                    {{ row.period_range ?? '-' }}
                                </div>
                            </div>
                        </template>
                    </el-table-column>

                    <!-- 2. Status Badge -->
                    <el-table-column label="当前状态" width="180" align="center">
                        <template #default="{ row }">
                            <div
                                class="status-badge"
                                :class="`status-${statusConfig[row.status]?.type || 'info'}`"
                            >
                                <span class="status-dot"></span>
                                {{ statusConfig[row.status]?.label || row.status }}
                            </div>
                        </template>
                    </el-table-column>

                    <!-- 3. Employees Stats -->
                    <el-table-column label="人员变动详情" min-width="300" align="center">
                        <template #default="{ row }">
                            <div class="stats-group" style="justify-content: center">
                                <div class="stat-item">
                                    <span class="stat-label">建档期人数</span>
                                    <span class="stat-num">{{ row.initial_employees }}</span>
                                </div>
                                <div class="stat-divider"></div>
                                <div class="stat-item">
                                    <span class="stat-label">调查期人数</span>
                                    <span class="stat-num">{{ row.current_employees }}</span>
                                </div>
                                <div class="change-badge" :class="getStaffChangeClass(row)">
                                    {{ formatStaffChangeValue(row) }}
                                </div>
                            </div>
                        </template>
                    </el-table-column>

                    <!-- 4. Version (Increased width for hover) -->
                    <el-table-column
                        label="版本历史"
                        width="180"
                        align="center"
                        class-name="col-overflow-visible"
                    >
                        <template #default="{ row }">
                            <div class="version-container">
                                <div
                                    v-if="getVersionCount(row.reporting_period) > 1"
                                    class="version-pill clickable"
                                    @click="handleViewHistory(row.reporting_period)"
                                >
                                    <span class="version-count">{{
                                        getVersionCount(row.reporting_period)
                                    }}</span>
                                    <span>History</span>
                                </div>
                                <div v-else class="version-pill">
                                    <span>V1.0</span>
                                </div>
                            </div>
                        </template>
                    </el-table-column>

                    <!-- 5. Last Update -->
                    <el-table-column label="最后更新" width="200" align="center">
                        <template #default="{ row }">
                            <div class="timestamp-text">{{ formatDate(row.updated_at) }}</div>
                        </template>
                    </el-table-column>

                    <!-- 6. Actions -->
                    <el-table-column label="操作" fixed="right" width="140" align="center">
                        <template #default="{ row }">
                            <el-button
                                v-if="row.editable"
                                type="primary"
                                round
                                size="small"
                                @click="handleViewReport(row)"
                                class="action-btn btn-primary-theme"
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-else
                                type="default"
                                round
                                size="small"
                                @click="handleViewReport(row)"
                                class="action-btn"
                            >
                                查看
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </div>

        <!-- Beautiful History Dialog -->
        <el-dialog
            v-model="showHistoryDialog"
            title="历史版本记录"
            width="720px"
            :close-on-click-modal="false"
            class="history-dialog"
        >
            <div v-if="historyTimelineData.length" class="history-dialog-body">
                <el-timeline class="history-timeline">
                    <el-timeline-item
                        v-for="item in historyTimelineData"
                        :key="item.__key"
                        :type="item.__timelineType"
                        :color="getTimelineColor(item.__timelineType)"
                        placement="top"
                        hide-timestamp
                    >
                        <div class="history-card">
                            <!-- Card Header -->
                            <div class="history-card__header">
                                <!-- Left: Time -->
                                <div class="history-time-badge">
                                    <el-icon>
                                        <clock />
                                    </el-icon>
                                    <span>{{
                                        item.submitted_at
                                            ? formatDate(item.submitted_at)
                                            : '未提交 / 草稿'
                                    }}</span>
                                </div>
                                <!-- Right: Status -->
                                <el-tag
                                    :type="item.__statusType"
                                    effect="dark"
                                    round
                                    size="small"
                                    style="font-weight: 600; border: none"
                                >
                                    {{ item.__statusLabel }}
                                </el-tag>
                            </div>

                            <!-- Card Body -->
                            <div class="history-card__body">
                                <div class="history-metrics">
                                    <!-- Start Count -->
                                    <div class="metric-item">
                                        <div class="metric-icon-box">
                                            <el-icon>
                                                <user />
                                            </el-icon>
                                        </div>
                                        <div class="metric-content">
                                            <span class="metric-label">建档期人数</span>
                                            <span class="metric-value">{{
                                                item.initial_employees ?? '-'
                                            }}</span>
                                        </div>
                                    </div>

                                    <div class="metric-separator"></div>

                                    <!-- End Count -->
                                    <div class="metric-item">
                                        <div class="metric-icon-box">
                                            <el-icon><user-filled /></el-icon>
                                        </div>
                                        <div class="metric-content">
                                            <span class="metric-label">调查期人数</span>
                                            <span class="metric-value">{{
                                                item.current_employees ?? '-'
                                            }}</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Rejection Zone -->
                                <div v-if="item.__showReject" class="reject-zone">
                                    <div class="reject-icon">
                                        <el-icon><warning-filled /></el-icon>
                                    </div>
                                    <div class="reject-content">
                                        <div class="reject-title">审核驳回</div>
                                        <div class="reject-desc">
                                            {{ item.__rejectInfo.reason }}
                                        </div>
                                        <div class="reject-meta">
                                            {{ item.__rejectInfo.department }} •
                                            {{ item.__rejectInfo.time }}
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Footer -->
                            <div class="history-card__footer">
                                <span class="version-id"
                                    >ID:
                                    {{ resolveReportId(item)?.toString().slice(-8) || '...' }}</span
                                >
                                <div class="view-snapshot-btn" @click="handleViewReport(item)">
                                    查看快照
                                    <el-icon>
                                        <right />
                                    </el-icon>
                                </div>
                            </div>
                        </div>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <el-empty v-else description="暂无历史记录" />
        </el-dialog>
    </div>
</template>

<style scoped>
/* --- Global Resets & Layout --- */
.report-list-demo {
    display: flex;
    flex-direction: column;
    min-height: 100vh;
    padding: 32px 48px;
    box-sizing: border-box;
    background-color: #f8fafc;
    color: #1e293b;
    font-family:
        'Inter',
        -apple-system,
        BlinkMacSystemFont,
        'Segoe UI',
        Roboto,
        sans-serif;
}

/* Header */
.page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding: 40px;
    background: linear-gradient(135deg, #4f46e5 0%, #818cf8 100%);
    border-radius: 24px;
    color: white;
    box-shadow: 0 20px 40px -12px rgba(79, 70, 229, 0.3);
}

.header-left {
    display: flex;
    align-items: center;
    gap: 24px;
}

.header-icon {
    font-size: 48px;
    background: rgba(255, 255, 255, 0.2);
    padding: 16px;
    border-radius: 16px;
    backdrop-filter: blur(8px);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.4);
}

.page-title {
    font-size: 28px;
    font-weight: 800;
    margin: 0 0 8px 0;
    letter-spacing: -0.02em;
    color: white;
}

.page-description {
    font-size: 15px;
    opacity: 0.9;
    margin: 0;
    font-weight: 400;
    color: white;
}

/* Operation Bar */
.table-operations {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
}

/* Unified Primary Button Style (Indigo Gradient) */
.btn-primary-theme {
    background: linear-gradient(135deg, #4f46e5 0%, #6366f1 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.25);
    transition: all 0.2s ease;
}

.btn-primary-theme:hover {
    background: linear-gradient(135deg, #4338ca 0%, #4f46e5 100%) !important;
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(79, 70, 229, 0.35);
}

.btn-primary-theme:active {
    transform: translateY(0);
}

.create-btn {
    height: 44px;
    padding: 0 28px;
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Table Card */
.table-card {
    background: #ffffff;
    border-radius: 24px;
    box-shadow: 0 10px 30px -5px rgba(0, 0, 0, 0.03);
    border: 1px solid rgba(241, 245, 249, 1);
    overflow: hidden;
    padding: 8px;
}

/* Modern Table Styles */
.modern-table {
    border-radius: 24px;

    --el-table-border-color: #f1f5f9;
    --el-table-row-hover-bg-color: #f8fafc;
    --el-table-header-bg-color: #f8fafc;
}

.cell-primary-text {
    font-size: 15px;
    font-weight: 600;
    color: #0f172a;
    margin-bottom: 4px;
}

.cell-secondary-text {
    font-size: 13px;
    color: #64748b;
    display: flex;
    align-items: center;
    gap: 6px;
}

.timestamp-text {
    font-variant-numeric: tabular-nums;
    color: #334155;
    font-size: 13px;
    font-weight: 500;
}

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    padding: 6px 12px;
    border-radius: 99px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1;
    transition: all 0.2s;
}

.status-dot {
    width: 6px;
    height: 6px;
    border-radius: 50%;
    margin-right: 8px;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.5);
}

.status-success {
    background: #ecfdf5;
    color: #059669;
    border: 1px solid #d1fae5;
}

.status-success .status-dot {
    background: #10b981;
}

.status-primary {
    background: #eff6ff;
    color: #2563eb;
    border: 1px solid #dbeafe;
}

.status-primary .status-dot {
    background: #3b82f6;
}

.status-warning {
    background: #fff7ed;
    color: #ea580c;
    border: 1px solid #ffedd5;
}

.status-warning .status-dot {
    background: #f97316;
}

.status-danger {
    background: #fef2f2;
    color: #dc2626;
    border: 1px solid #fee2e2;
}

.status-danger .status-dot {
    background: #ef4444;
}

.status-info {
    background: #f8fafc;
    color: #64748b;
    border: 1px solid #e2e8f0;
}

.status-info .status-dot {
    background: #94a3b8;
}

/* Stats Group */
.stats-group {
    display: flex;
    align-items: center;
    gap: 24px;
}

.stat-item {
    display: flex;
    flex-direction: column;
    min-width: 60px;
    align-items: center;
}

.stat-label {
    font-size: 11px;
    font-weight: 600;
    color: #94a3b8;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 4px;
}

.stat-num {
    font-size: 16px;
    font-weight: 700;
    font-variant-numeric: tabular-nums;
    color: #1e293b;
}

.stat-divider {
    width: 1px;
    height: 32px;
    background: #e2e8f0;
}

/* Change Badge */
.change-badge {
    margin-left: 20px;
    font-size: 13px;
    font-weight: 700;
    padding: 6px 10px;
    border-radius: 8px;
    font-variant-numeric: tabular-nums;
}

.change-indicator--increase {
    background: #f0fdf4;
    color: #16a34a;
}

.change-indicator--decrease {
    background: #fef2f2;
    color: #dc2626;
}

.change-indicator--flat {
    background: #f8fafc;
    color: #94a3b8;
}

.change-indicator--unknown {
    background: #f8fafc;
    color: #94a3b8;
}

/* Version Pill - Adjusted Padding & Container */
.version-container {
    display: flex;
    justify-content: center;
    width: 100%;
}

.version-pill {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    background: #fff;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 8px 16px;
    /* Larger padding for hover safety */
    font-size: 12px;
    color: #64748b;
    transition: all 0.2s;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    cursor: default;
}

.version-pill.clickable:hover {
    border-color: #818cf8;
    color: #4f46e5;
    transform: scale(1.05);
    /* Use scale instead of translate for smoother effect */
    box-shadow: 0 4px 12px rgba(79, 70, 229, 0.15);
    cursor: pointer;
    z-index: 1;
    /* Ensure it pops on top */
}

.version-pill.clickable:hover .version-count {
    background: #4f46e5;
    color: white;
}

.version-count {
    background: #e2e8f0;
    color: #475569;
    font-size: 11px;
    padding: 2px 6px;
    border-radius: px;
    margin-right: 8px;
    font-weight: 700;
    transition: all 0.2s;
}

/* --- BEAUTIFIED HISTORY STYLES --- */
.history-dialog :deep(.el-dialog) {
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 0 40px 80px -20px rgba(0, 0, 0, 0.2);
}

.history-dialog :deep(.el-dialog__header) {
    margin: 0;
    padding: 24px 32px;
    border-bottom: 1px solid #f1f5f9;
    background: #fff;
}

.history-dialog :deep(.el-dialog__title) {
    font-weight: 700;
    font-size: 18px;
    color: #0f172a;
}

/* NO SCROLLBAR (Hidden Sidebar) but scrollable */
.history-dialog-body {
    padding: 40px;
    max-height: 65vh;
    overflow-y: auto;
    background: #f8fafc;

    /* Hide scrollbar */
    -ms-overflow-style: none;
    /* IE and Edge */
    scrollbar-width: none;
    /* Firefox */
}

.history-dialog-body::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari, Opera */
}

/* Timeline Customization */
.history-timeline {
    padding-left: 8px;
}

/* Optimized Dot Style */
.history-timeline :deep(.el-timeline-item__node) {
    /* Keep background color from inline style (status color) */
    box-shadow: 0 0 0 4px white;
    /* White ring to separate from line */
    width: 12px;
    height: 12px;
}

.history-timeline :deep(.el-timeline-item__tail) {
    border-left: 2px solid #e2e8f0;
    left: 5px;
    top: 14px;
    /* Adjust tail start position */
    height: calc(100% - 14px);
}

/* The Beautiful Card */
.history-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.02),
        0 10px 15px -3px rgba(0, 0, 0, 0.02);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
    margin-top: 0;
    border: 1px solid transparent;
}

.history-card:hover {
    transform: translateY(-3px);
    box-shadow:
        0 20px 25px -5px rgba(0, 0, 0, 0.05),
        0 8px 10px -6px rgba(0, 0, 0, 0.01);
    border-color: rgba(79, 70, 229, 0.1);
}

.history-card__header {
    padding: 16px 24px;
    border-bottom: 1px solid #f8fafc;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.history-time-badge {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: #64748b;
    font-weight: 500;
    background: #f8fafc;
    padding: 4px 10px;
    border-radius: 8px;
}

.history-time-badge .el-icon {
    font-size: 14px;
    color: #94a3b8;
}

.history-card__body {
    padding: 24px;
}

.history-metrics {
    display: flex;
    align-items: center;
}

.metric-item {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 16px;
}

/* Unified Icon Color Style (Indigo for all) */
.metric-icon-box {
    width: 42px;
    height: 42px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    background: #eef2ff;
    color: #4f46e5;
    /* Unified Color */
    flex-shrink: 0;
}

.metric-content {
    display: flex;
    flex-direction: column;
}

.metric-label {
    font-size: 11px;
    color: #94a3b8;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.03em;
    margin-bottom: 4px;
}

.metric-value {
    font-size: 16px;
    font-weight: 700;
    color: #1e293b;
    font-variant-numeric: tabular-nums;
}

.metric-separator {
    width: 1px;
    height: 40px;
    background: #f1f5f9;
    margin: 0 32px;
}

.reject-zone {
    margin: 8px 0 0 0;
    /* Adjusted spacing */
    background: #fff1f2;
    border-radius: 12px;
    padding: 16px;
    border: 1px solid #fecdd3;
    display: flex;
    gap: 12px;
}

.reject-icon {
    color: #e11d48;
    font-size: 20px;
    margin-top: 2px;
}

.reject-content {
    flex: 1;
}

.reject-title {
    color: #9f1239;
    font-weight: 700;
    font-size: 13px;
    margin-bottom: 4px;
}

.reject-desc {
    color: #be123c;
    font-size: 13px;
    line-height: 1.5;
}

.reject-meta {
    margin-top: 8px;
    font-size: 11px;
    color: #e11d48;
    opacity: 0.8;
    font-weight: 500;
}

.history-card__footer {
    background: #fcfcfc;
    padding: 12px 24px;
    border-top: 1px solid #f1f5f9;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.version-id {
    font-family: 'JetBrains Mono', monospace;
    font-size: 11px;
    color: #94a3b8;
}

.view-snapshot-btn {
    font-size: 13px;
    font-weight: 600;
    color: #4f46e5;
    display: flex;
    align-items: center;
    gap: 4px;
    cursor: pointer;
    transition: gap 0.2s;
}

.view-snapshot-btn:hover {
    gap: 8px;
    color: #4338ca;
}

.mr-1 {
    margin-right: 4px;
}

.empty-state-card {
    background: white;
    border-radius: 24px;
    padding: 80px 0;
    text-align: center;
}

/* Allow hover effects to overflow table cells */
:deep(.el-table .col-overflow-visible .cell) {
    overflow: visible;
    padding: 0;
    /* Optional: Reset padding if needed to give more space, but visible overflow is key */
}
</style>
